﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using Traceability_Management.Domain;
using Traceability_Management.ErrorCode;
using Traceability_Management.Infrastructure.Interfaces;
using Traceability_Management.Read.Api.Application.Command.RabitsWay;

namespace Traceability_Management.Read.Api.Application.CommandHandler.RabitsWay
{
    public class UpdateRabitsCommandHandler : IRequestHandler<UpdateRabitsCommand, ApiResult<int>>
    {
        IBaseReponsitory<Rabits> Rabits;

        public UpdateRabitsCommandHandler(IBaseReponsitory<Rabits> Rabits)
        {
            this.Rabits = Rabits;
        }

        public async Task<ApiResult<int>> Handle(UpdateRabitsCommand request, CancellationToken cancellationToken)
        {
            var Bachlist = Rabits.GetQuery().Where(c => c.Rabit_Batch == request.Rabits.Rabit_Batch && !c.Rabit_IsDel&&c.Rabit_Id!= request.Rabits.Rabit_Id).ToList();
            if (Bachlist.Count > 0)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnum.False,
                    Message = "该批次号已存在",
                };
            }

            var list = Rabits.GetQuery().Where(c => c.SId == request.Rabits.SId && !c.Rabit_IsDel && c.Rabit_Id != request.Rabits.Rabit_Id).ToList();
            if (list.Count > 0)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnum.False,
                    Message = "该商品已有溯源",
                    Data = 0
                };
            }
  
                request.Rabits.UpdateTime = DateTime.Now;
                await Rabits.UpdateAsync(request.Rabits);
                return new ApiResult<int>
                {
                    Code = ApiEnum.Success,
                    Message = "修改成功",
                    Data = 1
                };
            

        }
    }
}
